package com.ruoyi.lvlian.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.util.Objects;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.InvoiceInfo;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.vo.WarehouseRefVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.domain.WarehouseRef;
import com.ruoyi.lvlian.service.IWarehouseRefService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import  com.ruoyi.lvlian.dto.WarehouseRefDto;

@RestController
@RequestMapping("/warehouseRef")
@Api(value = "2.4供应链关系", tags = "2.4供应链关系")
public class WarehouseRefController extends BaseController {
    @Autowired
    private IWarehouseRefService warehouseRefService;
    @Autowired
    private ICommonService iCommonService;
    /**
     * 查询销售物流关联采购物流列表
     */
    //@RequiresPermissions("lvlian:warehouseRef:list")
    @GetMapping("/list")
    public R<TableDataInfo> list(WarehouseRefDto warehouseRef) {
        if (SecurityUtils.getUserId() == 1) {
            warehouseRef.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());
            if (orgCodes.size() == 0) {
                return R.fail("暂未分配账本");
            }
            if (Objects.isNull(warehouseRef.getOrgCodes()) || warehouseRef.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                warehouseRef.setOrgCodes(orgCodes);
            }
        }
        startPage();
        List<WarehouseRefVo> list = warehouseRefService.selectWarehouseRefList(warehouseRef);
        return R.ok(getDataTable(list));
    }



    /**
     *
     */
    @ApiOperation("获取销售物流关联采购物流详细信息")
    @GetMapping(value = "/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "ID", required = true) @RequestParam(value = "id") String id) {
        return success(warehouseRefService.selectWarehouseRefById(id));
    }


    /**
     * 新增销售物流关联采购物流
     */
    //@RequiresPermissions("lvlian:warehouseRef:add")
    @Log(title = "销售物流关联采购物流", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WarehouseRef warehouseRef) {
        return toAjax(warehouseRefService.insertWarehouseRef(warehouseRef));
    }

    /**
     * 修改销售物流关联采购物流
     */
    //@RequiresPermissions("lvlian:warehouseRef:edit")
    @Log(title = "销售物流关联采购物流", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WarehouseRef warehouseRef) {
        return toAjax(warehouseRefService.updateWarehouseRef(warehouseRef));
    }

    /**
     * 删除销售物流关联采购物流
     */
    //@RequiresPermissions("lvlian:warehouseRef:remove")
    @Log(title = "销售物流关联采购物流", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(warehouseRefService.deleteWarehouseRefByIds(ids));
    }

    @ApiOperation("导入供应链关系")
    @PostMapping("/importInfo")
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<WarehouseRef> dtoList = null;
        try {
            dtoList = warehouseRefService.importInfo(file, "供应链关系", 3);
        } catch (Exception e) {
            e.printStackTrace();
            return error("模板错误");
        }
        int totalSussess = warehouseRefService.bachSave(dtoList);
        int total = dtoList.size();
        int totalFail = total - totalSussess;
        String msg = "解析到" + total + "条数据，" + "导入成功" +Math.min(totalSussess, total)    + "条，导入失败" + Math.max(totalFail, 0)   + "条！";

        return success(msg);
    }


    @PostMapping("/syncImgs")
    public AjaxResult syncImgs(
            @ApiParam(value = "出库单号", required = true) @RequestParam(value = "outNum", required = true)    String outNum,
            @RequestParam(value = "sellerContractNum", required = true) String sellerContractNum,
            @RequestParam(value = "outDate", required = true) String outDate,
            @RequestParam(value = "buyerContractNum", required = true) String buyerContractNum,
            @RequestParam(value = "inNum", required = true) String inNum,
            @RequestParam(value = "inDate", required = true) String inDate,
            @RequestParam(value = "col", required = true) String col
    ) {
        if (Stream.of(outNum, sellerContractNum, outDate, buyerContractNum, inNum, inDate).anyMatch(StringUtils::isBlank)) {
            return error("所有参数均为必填项");
        }
        int msg =0;
        try {
          msg = warehouseRefService.syncImgs(outNum, sellerContractNum, outDate,inNum, buyerContractNum, inDate, col);
        } catch (Exception e) {
            e.printStackTrace();
            return error("同步错误");
        }
        return success(msg);
    }

}
